package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.UpdateBatchItemAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.mvp.mine.DeleteAreaPriceModel;
import com.luck.easyfoodbatch.mvp.mine.DeleteAreaPricePresenter;
import com.luck.easyfoodbatch.mvp.mine.DeleteAreaPriceView;
import com.luck.easyfoodbatch.mvp.mine.DeleteBatchModel;
import com.luck.easyfoodbatch.mvp.mine.DeleteBatchPresenter;
import com.luck.easyfoodbatch.mvp.mine.DeleteBatchView;
import com.luck.easyfoodbatch.mvp.mine.EditBatchStockModel;
import com.luck.easyfoodbatch.mvp.mine.EditBatchStockPresenter;
import com.luck.easyfoodbatch.mvp.mine.EditBatchStockView;
import com.luck.easyfoodbatch.mvp.model.AddBatch;
import com.luck.easyfoodbatch.mvp.model.Batches;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.pickerview.PopBirthHelper;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.luck.easyrecyclerview.swipe.MyLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.ui
 * email：893855882@qq.com
 * data：16/11/4
 */
public class UpdateBatchActivity extends BaseActivity implements DeleteAreaPriceView, EditBatchStockView, DeleteBatchView {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_stock)
    EditText et_stock;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_save_batch)
    TextView tv_save_batch;
    @BindView(R.id.tv_update)
    TextView tv_update;
    private List<Batches.DataBean> list = new ArrayList<>();
    private UpdateBatchItemAdapter adapter;
    private DeleteAreaPriceModel deleteAreaPriceModel;
    private int position = 0;
    private PopBirthHelper birthHelper;
    private EditBatchStockModel stockModel;
    private DeleteBatchModel batchModel;
    private String gid = "", unit = "";
    private String stock = "";
    private int type = 0;
    private String title = "", rightTitle;
    private int num = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", 0);
        gid = getIntent().getStringExtra("gid");
        num = getIntent().getIntExtra("num", 0);
        if (type == 1) {
            title = "添加批次";
        } else {
            rightTitle = "删除该批次";
            title = "编辑批次";
        }
        setContentView(R.layout.ac_update_batch, title, rightTitle, MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        if (type == 1) {
            rightTitle = "";
            list = new ArrayList<>();
            Batches.DataBean bean = new Batches.DataBean();
            bean.setGid(-1);
            bean.setPrice("");
            bean.setSold_province_zh("");
            list.add(bean);
        } else {
            list = (List<Batches.DataBean>) getIntent().getSerializableExtra("list");
            if (list != null && list.size() > 0) {
                Batches.DataBean bean = list.get(0);
                String due_date = bean.getDue_date();
                stock = bean.getStock();
                unit = bean.getUnit();
                if (!Tools.isNull(due_date)) {
                    tvTime.setText(Tools.SubTime2(due_date + ""));
                } else {
                    tvTime.setText("");
                }
                et_stock.setText(stock);
                et_stock.setSelection(et_stock.getText().length());
            }
        }

        adapter = new UpdateBatchItemAdapter(mContext, list, onRemoveBatch, num);
        MyLayoutManager manager = new MyLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(manager);
        adapter.setUnit(unit);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new UpdateBatchItemAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Batches.DataBean dataBean = list.get(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("gid", gid);
                if (type == 1) {
                    // 添加售卖地区
                    if (Tools.isNull(tvTime)) {
                        T.showToast(mContext, "请先选择到期时间");
                        return;
                    }
                    if (Tools.isNull(et_stock)) {
                        T.showToast(mContext, "请先输入库存量");
                        return;
                    }
                    bundle.putString("due_date", tvTime.getText().toString().trim());
                    bundle.putString("stock", et_stock.getText().toString().trim());
                    bundle.putString("unit", dataBean.getUnit());
                    bundle.putString("price", dataBean.getPrice());
                    bundle.putString("batch_id", dataBean.getBatch_id() + "");
                    bundle.putString("sold_province", dataBean.getSold_province());
                    bundle.putString("single_price", dataBean.getSingle_price());
                    bundle.putString("sold_province_zh", dataBean.getSold_province_zh());
                    bundle.putInt("position", position);
                    if (dataBean.getGid() == -1) {
                        bundle.putInt("type", 1);
                    } else {
                        bundle.putInt("type", 0);
                    }
                    bundle.putDouble("mail", num);
                } else {
                    String price = dataBean.getPrice();
                    String sold_province = dataBean.getSold_province();
                    String sold_province_zh = dataBean.getSold_province_zh();
                    bundle.putString("due_date", tvTime.getText().toString().trim());
                    bundle.putString("stock", stock + "");
                    bundle.putString("unit", unit);
                    bundle.putString("price", price);
                    bundle.putString("batch_id", dataBean.getBatch_id() + "");
                    bundle.putString("single_price", dataBean.getSingle_price());
                    bundle.putString("sold_province", sold_province);
                    bundle.putString("sold_province_zh", sold_province_zh);
                    bundle.putDouble("mail", num);
                    bundle.putInt("position", position);
                    bundle.putInt("type", 0);
                }
                intent.setClass(mContext, AddSaleAreaActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 200);
            }
        });
        birthHelper = new PopBirthHelper(this);
        birthHelper.setOnClickOkListener(new PopBirthHelper.OnClickOkListener() {
            @Override
            public void onClickOk(String birthday) {
                tvTime.setText(birthday);
            }
        });
    }

    /**
     * 删除售卖地区
     */
    public UpdateBatchItemAdapter.OnRemoveBatch onRemoveBatch = new UpdateBatchItemAdapter.OnRemoveBatch() {
        @Override
        public void onRemoveBatch(int index, Batches.DataBean bean) {
            String batch_id = bean.getBatch_id() + "";
            position = index;// 要删除的下标
            showDeleteDialog(0, batch_id);
        }
    };

    @Override
    public void rightClick() {
        super.rightClick();
        String batch_ids = "";
        StringBuffer sb = new StringBuffer();
        for (Batches.DataBean item : list) {
            sb.append(item.getBatch_id()).append(",");
        }
        batch_ids = sb.toString();
        if (!Tools.isNull(batch_ids) && batch_ids.endsWith(",")) {
            batch_ids = batch_ids.substring(0, batch_ids.length() - 1);
        }
        showDeleteDialog(1, batch_ids);
    }

    /**
     * 删除售卖地区提示
     */
    private void showDeleteDialog(final int type, final String batch_id) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        final TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        switch (type) {
            case 0:
                tv_content.setText("确定删除该售卖地区吗？");
                break;
            case 1:
                tv_content.setText("确定删除该批次吗？");
                break;
        }

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog(getString(R.string.app_loading));
                switch (type) {
                    case 0:
                        deleteAreaPriceModel = new DeleteAreaPricePresenter(UpdateBatchActivity.this, mContext);
                        deleteAreaPriceModel.deleteAreaPrice(batch_id);
                        break;
                    case 1:
                        batchModel = new DeleteBatchPresenter(UpdateBatchActivity.this, mContext);
                        batchModel.deleteBatch(batch_id);
                        break;
                }

                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @OnClick({R.id.tv_time, R.id.tv_save_batch, R.id.tv_update})
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        String due_date = tvTime.getText().toString().trim();
        String stockStr = et_stock.getText().toString().trim();
        switch (v.getId()) {
            case R.id.tv_time:
                birthHelper.show(tvTime);
                break;
            case R.id.tv_save_batch:
                String batch_ids = "";
                StringBuffer sb = new StringBuffer();
                for (Batches.DataBean item : list) {
                    sb.append(item.getBatch_id()).append(",");
                }
                batch_ids = sb.toString();
                if (!Tools.isNull(batch_ids) && batch_ids.endsWith(",")) {
                    batch_ids = batch_ids.substring(0, batch_ids.length() - 1);
                }

                if (Tools.isNull(due_date)) {
                    T.showToast(mContext, "请选择到期日期");
                } else if (Tools.isNull(stockStr)) {
                    T.showToast(mContext, "请输入库存量");
                } else {
                    showProgressDialog(getString(R.string.app_loading));
                    stockModel = new EditBatchStockPresenter(this, mContext);
                    stockModel.editBatchStock(batch_ids, due_date, stockStr);
                }
                break;
            case R.id.tv_update:
                if (Tools.isNull(due_date)) {
                    T.showToast(mContext, "请选择到期日期");
                } else if (Tools.isNull(stockStr)) {
                    T.showToast(mContext, "请输入库存量");
                } else {
                    bundle.putString("gid", gid);
                    bundle.putString("due_date", tvTime.getText().toString().trim());
                    bundle.putString("stock", et_stock.getText().toString().trim());
                    bundle.putString("unit", unit);
                    bundle.putDouble("mail", num);
                    bundle.putInt("type", 1);
                    intent.setClass(mContext, AddSaleAreaActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                }
                break;
        }
    }

    @Override
    public void deleteAreaPriceSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                if (list.size() > 0 && list != null) {
                    list.remove(position);
                    adapter.notifyDataSetChanged();
                }
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void editBatchStockSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void deleteBatchSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        AddBatch.DataBean item = (AddBatch.DataBean) data.getSerializableExtra("data");
                        if (item != null) {
                            int position = data.getIntExtra("position", -1);
                            int type = data.getIntExtra("type", 0);
                            if (type == 0) {
                                // 编辑
                                Batches.DataBean bean = list.get(position);
                                bean.setGid(Integer.parseInt(item.getGid()));
                                bean.setSold_province_zh(item.getSold_province_zh());
                                bean.setSold_province(item.getSold_province());
                                bean.setPrice(item.getPrice());
                                bean.setBatch_id(item.getBatch_id());
                                bean.setCreated_at(item.getCreated_at());
                                bean.setDue_date(item.getDue_date() + "");
                                bean.setStock(item.getStock());
                                bean.setUnit(bean.getUnit());
                                bean.setUpdated_at(bean.getUpdated_at());
                                bean.setSingle_price(item.getSingle_price());
                            } else {
                                Batches.DataBean dataBean = new Batches.DataBean();
                                dataBean.setGid(Integer.parseInt(item.getGid()));
                                dataBean.setSold_province_zh(item.getSold_province_zh());
                                dataBean.setSold_province(item.getSold_province());
                                dataBean.setPrice(item.getPrice());
                                dataBean.setBatch_id(item.getBatch_id());
                                dataBean.setCreated_at(item.getCreated_at());
                                dataBean.setDue_date(item.getDue_date() + "");
                                dataBean.setStock(item.getStock());
                                dataBean.setUnit(dataBean.getUnit());
                                dataBean.setUpdated_at(dataBean.getUpdated_at());
                                dataBean.setSingle_price(item.getSingle_price());
                                if (type == 1) {
                                    // 如果是添加批次,并且只有一条数据，判断此条数据是否为默认数据
                                    if (list.size() == 1) {
                                        Batches.DataBean bean = list.get(0);
                                        if (bean.getGid() == -1) {
                                            list.clear();
                                        }
                                    }
                                }
                                list.add(dataBean);
                            }
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    break;
            }
        }
    }
}
